<!DOCTYPE html>
<html>
<head>
    <title>授权码管理</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vue@3.3.4/dist/vue.global.min.js"></script>
    <style>
        .token-container {
            max-width: 1200px;
            margin: 50px auto;
            padding: 20px;
        }
        .token-list {
            margin-top: 20px;
        }
        .token-item {
            padding: 15px;
            border: 1px solid #ddd;
            margin-bottom: 10px;
            border-radius: 5px;
            word-break: break-all;
        }
        .token-item:hover {
            background-color: #f8f9fa;
        }
        .token-info {
            display: flex;
            align-items: center;
            gap: 15px;
            margin-bottom: 8px;
            color: #666;
        }
        .token-code {
            display: flex;
            align-items: center;
            gap: 10px;
            background-color: #f8f9fa;
            padding: 8px;
            border-radius: 4px;
        }
        .copy-btn {
            padding: 2px 8px;
            font-size: 0.9em;
            cursor: pointer;
            margin-left: auto;
        }
        [v-cloak] { display: none; }
    </style>
</head>
<body>
    <div id="app" class="container token-container" v-cloak>
        <div v-if="!isLoggedIn">
            <h2 class="mb-4">授权码管理</h2>
            <div class="mb-3">
                <label for="password" class="form-label">管理员密码</label>
                <input type="password" class="form-control" v-model="password">
            </div>
            <button class="btn btn-primary" @click="verifyPassword">验证</button>
        </div>

        <div v-else>
            <h2 class="mb-4">创建授权码</h2>
            <div class="mb-3">
                <label for="expireDays" class="form-label">有效期（天）</label>
                <input type="number" class="form-control" v-model="expireDays">
            </div>
            <div class="mb-3">
                <label for="remark" class="form-label">备注</label>
                <input type="text" class="form-control" v-model="remark">
            </div>
            <button class="btn btn-primary me-2" @click="generateToken">生成授权码</button>
            <button class="btn btn-secondary" @click="logout">退出</button>

            <div class="token-list mt-4">
                <h3>授权码列表(只显示在当前机器创建的)</h3>
                <div class="token-items">
                    <div v-for="token in tokens" :key="token.code" class="token-item">
                        <div class="token-info">
                            <span><strong>备注：</strong>[[token.remark || '无']]</span>
                            <span>
                                <strong>状态：</strong>
                                <span class="text-success" v-if="token.is_valid">有效</span>
                                <span class="text-danger" v-else>已过期</span>
                            </span>
                            <span><strong>有效期至：</strong>[[token.expire_time]]</span>
                        </div>
                        <div class="token-code">
                            <span>[[token.code]]</span>
                            <button class="btn btn-sm btn-outline-primary copy-btn" @click="copyToken(token.code)">复制</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 添加全局fetch拦截器
        const originalFetch = window.fetch;
        window.fetch = async function(url, options = {}) {
            try {
                // 请求拦截
                const adminToken = localStorage.getItem('admin_token');
                if (adminToken && options.headers) {
                    options.headers['Authorization'] = adminToken;
                }

                // 发送请求
                const response = await originalFetch(url, options);
                
                // 克隆响应以避免消费原始响应流
                const clonedResponse = response.clone();
                try {
                    // 尝试解析响应JSON
                    const data = await clonedResponse.json();
                    // 检查响应状态
                    if (data.code !== 0) {
                        throw new Error(data.msg || '请求失败');
                    }
                    return response;
                } catch (error) {
                    throw error;
                }
            } catch (error) {
                alert(error.message);
                throw error;
            }
        };

        const { createApp, ref, onMounted } = Vue;

        createApp({
            delimiters: ['[[', ']]'],
            setup() {
                const isLoggedIn = ref(false);
                const password = ref('');
                const expireDays = ref(30);
                const remark = ref('');
                const tokens = ref([]);

                // 验证密码
                async function verifyPassword() {
                    if (!password.value) {
                        alert('请输入密码');
                        return;
                    }
                    try {
                        const response = await fetch('/verify_admin', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json'
                            },
                            body: JSON.stringify({ password: password.value })
                        });
                        const data = await response.json();
                        if (data.code === 0) {
                            localStorage.setItem('admin_token', data.token);
                            localStorage.setItem('admin_password', password.value);
                            isLoggedIn.value = true;
                            loadTokens();
                        }
                    } catch (error) {
                        console.error('验证失败：', error);
                    }
                }

                // 生成授权码
                async function generateToken() {
                    if (!expireDays.value) {
                        alert('请输入有效期');
                        return;
                    }
                    try {
                        const response = await fetch('/generate_token', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': localStorage.getItem('admin_token')
                            },
                            body: JSON.stringify({
                                expire_days: expireDays.value,
                                remark: remark.value
                            })
                        });
                        const data = await response.json();
                        if (data.code === 0) {
                            alert('授权码生成成功！');
                            loadTokens();
                            // 清空表单
                            expireDays.value = 30;
                            remark.value = '';
                        }
                    } catch (error) {
                        console.error('生成失败：', error);
                    }
                }

                // 加载授权码列表
                async function loadTokens() {
                    try {
                        const response = await fetch('/list_tokens', {
                            headers: {
                                'Authorization': localStorage.getItem('admin_token')
                            }
                        });
                        const data = await response.json();
                        if (data.code === 0) {
                            tokens.value = data.data;
                        }
                    } catch (error) {
                        console.error('加载失败：', error);
                    }
                }

                // 退出登录
                function logout() {
                    localStorage.removeItem('admin_token');
                    isLoggedIn.value = false;
                    password.value = '';
                    tokens.value = [];
                }

                // 复制授权码
                async function copyToken(token) {
                    try {
                        await navigator.clipboard.writeText(token);
                        alert('复制成功！');
                    } catch (error) {
                        console.error('复制失败：', error);
                        alert('复制失败，请手动复制');
                    }
                }

                // 组件挂载时检查是否已登录
                onMounted(() => {
                    const savedToken = localStorage.getItem('admin_token');
                    const savedPassword = localStorage.getItem('admin_password');
                    if (savedToken && savedPassword) {
                        password.value = savedPassword;
                        verifyPassword();
                    }
                });

                return {
                    isLoggedIn,
                    password,
                    expireDays,
                    remark,
                    tokens,
                    verifyPassword,
                    generateToken,
                    logout,
                    copyToken
                };
            }
        }).mount('#app');
    </script>
</body>
</html> 